/**************************************************************************************** 
 Copyright © 2003-2012 ZTEsoft Corporation. All rights reserved. Reproduction or       <br>
 transmission in whole or in part, in any form or by any means, electronic, mechanical <br>
 or otherwise, is prohibited without the prior written consent of the copyright owner. <br>
 ****************************************************************************************/
package com.iwhalecloud.bss.kite.cucc.web.service.accept.util;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.DateFormatUtils;
import com.iwhalecloud.bss.kite.dataservice.cache.ProdFeeCache;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttrValue;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.service.scene.attr.OperateInstAttrService;
import com.ztesoft.bss.common.util.SpringUtil;

/** 
 * <Description>资费产品处理 <br> 
 *  
 * @author tengg<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2022年3月16日 <br>
 * @since R9.0<br>
 * @see com.iwhalecloud.bss.kite.cucc.web.service.accept.util <br>
 */

public class ProductFeeInstUtils {
    /**
     * Description: <br> 
     *  预销户处理： 根据销户原因处理趸交资费的是否收取违约金，违约金收取方式
     * @author tengg<br>
     * @taskId <br>
     * @param sceneInstId
     * @param custId <br>
     */
    public static void  dealOneOffFeeFalsify(String sceneInstId, String value) {
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        String isInitPageRenderFlag = querySceneInstService.getExtParameterValue(sceneInstId, "isInitPageRenderFlag");
        // 场景初始化时，不执行
        if (KiteStringUtils.isEqual(isInitPageRenderFlag, LocalKeyConsts.IFTRUE_T)) {
            return ;
        }
        
        // 查询已生效趸交资费
        List<KiteInst> additionalInsts = listOneOffFee(sceneInstId, querySceneInstService);
        if (KiteListUtils.isEmpty(additionalInsts)) {
            return;
        }
        IOperateSceneInstService operateSceneInstService = SpringUtil.getBean(IOperateSceneInstService.class);
        additionalInsts.forEach(kiteInst ->{
            List<KiteAttr> attrs = Lists.newArrayList();
            // 是否收取违约金
            KiteAttr collectionFalsifyAttr = kiteInst.getAttr("210004554");
            // 违约金收取方式
            KiteAttr collectionMethodAttr = kiteInst.getAttr("210004555");
            // 销户原因： 6-联通原因-搬迁无资源无需赔偿
            if (KiteStringUtils.isEqual(value, "6")) {
                // 联通原因销户，是否收取违约金：否
                setAttrValue(collectionFalsifyAttr, "1_0000107", attrs);
                // 联通原因销户，违约金收取方式：不收取
                setAttrValue(collectionMethodAttr, "", attrs);
            }
            else {
                // 非联通原因销户，是否收取违约金：是
                setAttrValue(collectionFalsifyAttr, "1_0000106", attrs);
                // 非联通原因销户，违约金收取方式：后台计算
                setAttrValue(collectionMethodAttr, "110007676", attrs);
            }
            if (KiteListUtils.isNotEmpty(attrs)) {
                operateSceneInstService.setAttrs(sceneInstId, kiteInst.getInstType(), kiteInst.getInstId(), attrs);
                KiteOfferInst additionalKiteOfferInst = querySceneInstService.getOfferInst(kiteInst.getOwnerCustId(), kiteInst.getInstId());
                if (Objects.nonNull(additionalKiteOfferInst) && KiteStringUtils.isEqual(additionalKiteOfferInst.getActionType().name(), ActionType.K.name())) {
                    additionalKiteOfferInst.setActionType(ActionType.M);
                    operateSceneInstService.addAdditionalOfferInst(sceneInstId, additionalKiteOfferInst);
                }
            }
        });
    }
    
    /**
     * Description: <br> 
     *  预销户处理趸交资费失效时间
     * @author tengg<br>
     * @taskId <br>
     * @param sceneInstId <br>
     */
    public static void dealOneOffFeeExpireTime(String sceneInstId) {
        
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        String isInitPageRenderFlag = querySceneInstService.getExtParameterValue(sceneInstId, "isInitPageRenderFlag");
        // 场景初始化时，不执行
        if (KiteStringUtils.isEqual(isInitPageRenderFlag, LocalKeyConsts.IFTRUE_T)) {
            return ;
        }
        String taskCode = querySceneInstService.getExtParameterValue(sceneInstId, "taskCode");
        KiteAttr stopRentTimeAttr = querySceneInstService.getCommonAttrsByFieldName(sceneInstId, "REC10033", "207");
        //止租时间
        KiteAttr terminationTimeAttr = querySceneInstService.getCommonAttr(sceneInstId, "ORD10123");

        //止租方式
        KiteAttr terminationMethodAttr = querySceneInstService.getCommonAttr(sceneInstId, "ORD10111");
        if (KiteObjectUtils.isEmpty(terminationMethodAttr) && !"OrderStopRent".equalsIgnoreCase(taskCode)) {
            return;
        }
        // 查询已生效趸交资费
        List<KiteInst> additionalInsts = listOneOffFee(sceneInstId, querySceneInstService);
        if (KiteListUtils.isEmpty(additionalInsts)) {
            return;
        }
        
        additionalInsts.forEach(kiteInst ->{
            // 失效时间
            KiteAttr endDateAttr = kiteInst.getAttr("200000173");
            String newEndDateValue = "";
            //止租环节
            if ("OrderStopRent".equalsIgnoreCase(taskCode)) {
                if (KiteObjectUtils.allNotNull(stopRentTimeAttr) && KiteStringUtils.isNotEmpty(stopRentTimeAttr.getValue())
                    && DateFormatUtils.compareDate(endDateAttr.getValue(), stopRentTimeAttr.getValue(), DateFormatUtils.DATE_TIME_FORMAT)>0) {
                    Date date = DateFormatUtils.getEndOfDay(DateFormatUtils.parseDateToFormat(stopRentTimeAttr.getValue(), DateFormatUtils.DATE_FORMAT));
                    newEndDateValue = DateFormatUtils.formatDate(date, DateFormatUtils.DATE_TIME_FORMAT);
                }
            }
            else {
             // 止租方式： 1-手动止租
                if (KiteObjectUtils.allNotNull(terminationMethodAttr) && KiteStringUtils.equals(terminationMethodAttr.getValue(), "1")) {
                    // 失效时间的当前值和原始值不相等的时候，需要将当前值还原为原始值
                    if (!KiteStringUtils.isEqual(endDateAttr.getValue(), endDateAttr.getOriginValue())) {
                        newEndDateValue = endDateAttr.getOriginValue();
                    }
                }
                else {
                   if (KiteObjectUtils.allNotNull(terminationTimeAttr) && KiteStringUtils.isNotEmpty(terminationTimeAttr.getValue())
                       && DateFormatUtils.compareDate(endDateAttr.getValue(), terminationTimeAttr.getValue(), DateFormatUtils.DATE_TIME_FORMAT)>0) {
                       newEndDateValue = terminationTimeAttr.getValue();
                   }
                }
            }
            
            if (KiteStringUtils.isNotEmpty(newEndDateValue)) {
                OperateInstAttrService operateInstAttrService = SpringUtil.getBean(OperateInstAttrService.class);
                operateInstAttrService.setAttrValue(kiteInst, endDateAttr.getFieldName(), newEndDateValue, sceneInstId, null);
                KiteOfferInst additionalKiteOfferInst = querySceneInstService.getOfferInst(kiteInst.getOwnerCustId(), kiteInst.getInstId());
                if (Objects.nonNull(additionalKiteOfferInst) && KiteStringUtils.isEqual(additionalKiteOfferInst.getActionType().name(), ActionType.K.name())) {
                    additionalKiteOfferInst.setActionType(ActionType.M);
                    IOperateSceneInstService operateSceneInstService = SpringUtil.getBean(IOperateSceneInstService.class);
                    operateSceneInstService.addAdditionalOfferInst(sceneInstId, additionalKiteOfferInst);
                }
            }
        });
    }
    
    /**
     * Description: <br> 
     *  查询已生效趸交资费
     * @author tengg<br>
     * @taskId <br>
     * @param sceneInstId
     * @return <br>
     */
    private static List<KiteInst> listOneOffFee(String sceneInstId, IQuerySceneInstService querySceneInstService) {
        List<KiteInst> additionalInsts = querySceneInstService.listInsts(sceneInstId, Arrays.asList(InstType.ADDITIONAL_OFFER_INST));
        if (KiteListUtils.isNotEmpty(additionalInsts)) {
            additionalInsts.removeIf(additionalOfferInst -> {
                KiteAttr startDateAttr = additionalOfferInst.getAttr(LocalKeyConsts.STARTING_DATE_FIELD_NAME);
                if (KiteObjectUtils.allNotNull(startDateAttr) && KiteStringUtils.isNotEmpty(startDateAttr.getValue())
                    && DateFormatUtils.compareDate(startDateAttr.getValue(), DateFormatUtils.getFormatedDateTime(), DateFormatUtils.DATE_TIME_FORMAT)>0) {
                    return true;
                }
                Map<String, Object> offerMap = Optional.ofNullable(ProdFeeCache.get(additionalOfferInst.getSpecId())).map(Offer::getOfferMap).orElse(null);
                if (!LocalKeyConsts.FEE_PAY_TYPE_ONE_OFF.equals(KiteMapUtils.getString(offerMap, "payType"))) {
                    return true;
                }
                return false;
            });
        }
        
        return additionalInsts;
    }
    
    private static void setAttrValue(KiteAttr kiteAttr, String value, List<KiteAttr> attrs) {
        if (KiteObjectUtils.allNotNull(kiteAttr) && !KiteStringUtils.isEqual(value, kiteAttr.getValue())) {
            kiteAttr.setValue(value);
            kiteAttr.setValueDesc(value);
            List<KiteAttrValue> attrValues = kiteAttr.getAttrValues();
            attrValues.forEach(attrvalue -> {
                if (KiteStringUtils.isEqual(value, attrvalue.getAttrValue())) {
                    kiteAttr.setValueDesc(attrvalue.getAttrValueName());
                }
            });
            if (KiteStringUtils.isEmpty(value)) {
                kiteAttr.setShowType(LocalKeyConsts.PROD_ATTR_SHOW_TYPE_H);
            }
            else {
                kiteAttr.setShowType(LocalKeyConsts.PROD_ATTR_SHOW_TYPE_D);
                kiteAttr.setIsEdit(LocalKeyConsts.IFTRUE_T);
            }
            attrs.add(kiteAttr);
        }
    }
}
